﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Model;
using Utility;
using Microsoft.AspNetCore.Http;

namespace api
{
    public class AuthFilterFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            bool isSkip = false;
            //controller验证
            if (context.Controller.GetType().GetCustomAttributes(typeof(SkipActionFilterAttribute), true).Any())
                isSkip = true;
            //Action验证
            if (!isSkip && context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                if (controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                   .Any(a => a.GetType().Equals(typeof(SkipActionFilterAttribute))))
                    isSkip = true;
            }
            if (!isSkip)
            {
                var userToken = JwtHelp.GetToken(context.HttpContext.Request.Headers["Authorization"].ToString()); //获取token信息
                string token = context.HttpContext.Request.Headers["Authorization"].ToString();

                if (userToken.code > 0)
                {
                    context.Result = new JsonResult(userToken);
                }
                if (String.IsNullOrEmpty(token))
                    context.Result = new JsonResult(new ResultData(StatusCodes.Status401Unauthorized));
                UserCache userCache = null;
                try
                {
                    userCache = RedisBase.Item_Get<UserCache>(token);

                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.ToString());
                }

                if (userCache == null)
                {
                    context.Result = new JsonResult(new ResultData(StatusCodes.Status401Unauthorized));
                }
                else
                {
                     
                }
            }
            base.OnActionExecuting(context);
        }
    }
}
